package tp.pr4.instructions;

import java.util.StringTokenizer;

import tp.pr4.NavigationModule;
import tp.pr4.RobotEngine;
import tp.pr4.instructions.exceptions.InstructionExecutionException;
import tp.pr4.instructions.exceptions.WrongInstructionFormatException;
import tp.pr4.items.ItemContainer;

public class PickInstruction
	extends java.lang.Object
	implements Instruction {
	
	private String itemToPick;
	private NavigationModule navigation;
    private ItemContainer robotContainer;

	public Instruction parse(java.lang.String cad) throws WrongInstructionFormatException
	{
		StringTokenizer instructionToken = new StringTokenizer(cad);
	    if(instructionToken.countTokens()!=2) 
			throw new WrongInstructionFormatException();
		
		String action=instructionToken.nextToken();
		if (!(action.toUpperCase().equalsIgnoreCase("PICK") || action.toUpperCase().equalsIgnoreCase("Coger")))
			throw new WrongInstructionFormatException();
		
		itemToPick=instructionToken.nextToken();
		return this;		
	}
	
	public void execute() throws InstructionExecutionException
	{
		if(!navigation.findItemAtCurrentPlace(itemToPick))
			throw new InstructionExecutionException("WALL·E says: Ooops, this place has not the object "+itemToPick + "\n");
		if(robotContainer.containsItem(itemToPick))
			throw new InstructionExecutionException("WALL·E says: I am stupid! I already have the object "+itemToPick +"\n");
		try
			{
			 robotContainer.addItem(navigation.pickItemFromCurrentPlace(itemToPick));
			 System.out.println("WALL·E says: I am happy! Now I have "+ itemToPick);
			}catch(Exception e){
				throw new InstructionExecutionException(e.getMessage());
			}
	}
	
	public java.lang.String getHelp()
	{
		return ("PICK | COGER <id>");
	}
	public void configureContext(RobotEngine engine, 
            NavigationModule navigation,
            ItemContainer robotContainer)
	{
	 	this.navigation=navigation;
	 	this.robotContainer=robotContainer;
	}
	
}
